package org.zzk.dao;

import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import io.netty.channel.Channel;

public class RoomManager {
    private static final RoomManager INSTANCE = new RoomManager();
    private final ConcurrentHashMap<String, Room> rooms = new ConcurrentHashMap<>();

    public static RoomManager getInstance() {
        return INSTANCE;
    }

    public Optional<Room> getRoom(String roomId) {
        return Optional.ofNullable(rooms.get(roomId));
    }

    public void addRoom(Room room) {
        rooms.put(room.getId(), room);
    }

    public void removeRoom(String roomId) {
        rooms.remove(roomId);

    }

    public String removeRoom(Channel ch) {
        for (Room room : rooms.values()) {
            for (Player player : room.getPlayers()) {
                if (player.getChannel().equals(ch)) {
                    synchronized (this) {
                        rooms.remove(room.getId());
                        return room.getId();
                    }
                }
            }
        }
        return "";
    }

}
